using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;


namespace FinlogiK.FxCop.Statistics
{
	/// <summary>
	/// 
	/// </summary>
	internal static class DbUtility
	{
		#region Methods

		internal static IDbConnection OpenConnection(string connectionString)
		{
			IDbConnection connection = new SqlConnection(connectionString);
			connection.Open();

			return connection;
		}

		internal static IDbDataParameter AddParameter(IDbCommand command, string name, DbType dbType, object value)
		{
			return DbUtility.AddParameter(command, name, dbType, 0, value);
		}

		internal static IDbDataParameter AddParameter(IDbCommand command, string name, DbType dbType, int size, object value)
		{
			return DbUtility.AddParameter(command, name, dbType, size, ParameterDirection.Input, value);
		}

		internal static IDbDataParameter AddParameter(IDbCommand command, string name, DbType dbType, ParameterDirection direction, object value)
		{
			return DbUtility.AddParameter(command, name, dbType, 0, direction, value);
		}

		internal static IDbDataParameter AddParameter(IDbCommand command, string name, DbType dbType, int size, ParameterDirection direction, object value)
		{
			IDbDataParameter parameter = command.CreateParameter();
			parameter.ParameterName = "@" + name;
			parameter.DbType = dbType;
			parameter.Size = size;
			parameter.Direction = direction;
			parameter.Value = value;

			command.Parameters.Add(parameter);

			return parameter;
		}

		internal static void SetParameterValue(object parameter, object value)
		{
			((IDbDataParameter)parameter).Value = value;
		}

		internal static void PrepareParameters(IDbCommand command)
		{
			foreach (IDbDataParameter parameter in command.Parameters)
			{
				if (parameter.Value == null)
				{
					parameter.Value = DBNull.Value;
				}
				else
				{
					switch (parameter.DbType)
					{
						case DbType.AnsiString:
						case DbType.AnsiStringFixedLength:
						case DbType.String:
						case DbType.StringFixedLength:
							if ((parameter.Size >= 0) && (((string)parameter.Value).Length > parameter.Size))
							{
								throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
									"The {0} parameter value exceeds the specified maximum size of {1}.",
									parameter.ParameterName, parameter.Size));
							}
							break;
					}
				}
			}
		}

		#endregion
	}
}